package com.llyb.chap07;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.SynchronousQueue;

public class SynchronousQueueDemo {


    public static void main(String[] args) {
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        Object printLock = new Object();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    queue.put(String.valueOf(i));
                    synchronized (printLock) {
                        System.out.println("即将放入元素");
                        System.out.println("队列已放入" + i);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Producer").start();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    String poll = queue.take();
                    synchronized (printLock) {
                        System.out.println("==========即将取出元素");
                        System.out.println("==========已取出：" + poll);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Consumer").start();
    }
}
